<style>
.mui-btn .mui-spinner {
  width: 40px !important;
  height: 40px !important;
}
.mui-toast-container1 {
  bottom: 50px !important;
}
</style>
<style lang="less" scoped>
.login {
  background: url("./assets/loginbg.png") no-repeat top center fixed;
  background-size: 100% 410px;
  display: flex;
  justify-content: center;
  height: 100%;
  position: relative;
  overflow: hidden;
  background-color: #fff;

  .content {
    position: absolute;
    top: 474px;

    .user-info-bg {
      width: 600px;
      height: 96px;
      border-radius: 8px;
      background-color: rgba(241, 241, 241, 1);
      display: flex;
      align-items: center;
      padding-left: 40px;
    }
    .user-info-username {
      .user-info-bg;
    }
    .user-info-pwd,
    .user-info-pwd-message {
      margin-top: 30px;
      .user-info-bg;
    }

    .form-input {
      width: 462px;
      border-radius: 16px;
      background-color: rgba(241, 241, 241, 1);
      font-size: 28px;
      border: none;
      margin-bottom: 0;
      line-height: normal;
      padding: 0 0 0 40px;
    }

    .user-info-pwd-message {
      .form-input {
        width: 362px;
      }
      .get-validate-code {
        width: 128px;
        height: 56px;
        line-height: 56px;
        border-radius: 4px;
        background-color: rgba(81, 104, 255, 1);
        color: rgba(255, 255, 255, 1);
        padding: 0;
        text-align: center;
        vertical-align: text-bottom !important;
        position: absolute;
        right: 40px;
        font-size: 30px;
        &:active {
          background: #3c56e3;
        }
      }
    }
    .jeicon-eye {
      position: absolute;
      right: 28px;
      font-size: 24px;
    }
    .jeicon-eye-close {
      position: absolute;
      right: 30px;
      font-size: 30px;
    }

    input::-webkit-input-placeholder {
      color: #aab2bd;
    }

    .pwd {
      margin-top: 30px;
      display: flex;
      justify-content: space-between;
      width: 100%;
      height: 40px;
      line-height: 40px;
      color: rgba(81, 104, 255, 1);

      label {
        font-size: 28px;
      }
    }

    .login-btn {
      margin-top: 96px;
      width: 600px;
      height: 96px;
      border-radius: 16px;
      background-color: #536dfe;
      box-shadow: 0px 5px 12px 0px rgba(83, 109, 254, 0.44);
      // line-height: 66px;
      color: rgba(255, 255, 255, 1);
      font-size: 36px;
      &:active {
        background: #3c56e3;
      }
    }

    .register-btn {
      margin-top: 84px;
      height: 44px;
      line-height: 44px;
      color: rgba(83, 109, 254, 1);
      font-size: 32px;
      text-align: justify;
      display: flex;
      justify-content: center;
      //width: 100%;
    }

    .other-login {
      margin-top: 90px;
      padding-left: 80px;
      padding-right: 80px;
      display: flex;
      margin-bottom: 68px;
      justify-content: space-around;
      .jeicon {
        font-size: 60px;
        color: #cfcfcf;
      }
    }
  }

  .logon-content {
    width: 100%;
    text-align: center;
    .logo {
      height: 138px;
      width: 132px;
      position: relative;
      top: 120px;
      text-align: center;
    }
  }
}

.jeicon {
  color: #cfcfcf;
  font-size: 32px;
}
.user-list-span {
  transform: rotate(90deg);
  line-height: 1.28rem;
  text-align: center;
  float: right;
  height: 100%;
  // width:100%;
}
</style>

<template>
  <div class="login">
    <div class="logon-content">
      <img
        @tap="setServerPath"
        src="./assets/logo.png"
        class="logo"
      >
    </div>
    <div class="content">
      <div class="user-info-username">
        <i class="jeicon jeicon-user-o" />
        <input
          ref="inputBlurName"
          v-model="loginInfo.phone"
          @focus="inputfocus"
          type="text"
          placeholder="手机号/账户"
          class="form-input"
          maxlength="11"
        >
        <span
          @tap="loginHistory(false)"
          v-show="hasLoginHistory"
          class="user-list-span"
        >
          <i class="jeicon jeicon-angle-right user-list" />
        </span>
      </div>
      <div
        v-show="loginState"
        class="user-info-pwd"
      >
        <i class="jeicon jeicon-lock" />
        <input
          ref="inputBlurPassword"
          v-model="loginInfo.pwd"
          :type="showPwd ? 'password' : 'text'"
          @keyup.enter="login"
          @focus="inputfocus"
          placeholder="密码"
          class="form-input"
          maxlength="20"
        >
        <i
          :class="['jeicon','viewpwd',{
            'jeicon-eye': showPwd,
            'jeicon-eye-close': !showPwd
          }]"
          @tap="showPwd=!showPwd"
          class="jeicon viewpwd"
        />
      </div>
      <div
        v-show="!loginState"
        class="user-info-pwd-message"
      >
        <i class="jeicon jeicon-lock " />
        <input
          v-model="loginInfo.validateCode"
          type="number"
          placeholder="短信动态密码"
          class="form-input"
          oninput="if(value.length>6)value=value.slice(0,6)"
          maxlength="6"
          pattern="\d*"
        >
        <button
          @tap="getValidateCode"
          class="get-validate-code"
        >
          <span v-show="sendAuthCode">获取</span>
          <span v-show="!sendAuthCode">{{ auth_time }}s</span>
        </button>
      </div>
      <div class="pwd">
        <label
          v-show="loginState"
          @tap="loginState=!loginState,loginInfo.validateCode='',showPwd=true;"
        >动态密码登录</label>
        <label
          v-show="!loginState"
          @tap="loginState=!loginState,loginInfo.pwd=''"
        >个人密码登录</label>
        <label @tap="forgetPwd">忘记密码？</label>
      </div>
      <button
        ref="loginBtn"
        @tap="login"
        data-loading-text="登录中..."
        class="login-btn mui-btn"
      >
        登录
      </button>
      <span
        v-if="showRegister"
        class="register-btn"
      >
        <span @tap="register">立即注册</span>
      </span>
    </div>

    <sel-company-list
      ref="selCompanList"
      :company-list="companyList"
      :state="loginState"
      :showModalFlag="showModalFlag"
      :user-info="loginInfo"
      :app-login="appLoginInfo"
      @showFlag="showFlag"
      type="loginPage"
    >
      <div slot="modalTitle">
        选择企业
      </div>
    </sel-company-list>
  </div>
</template>

<script>
import {
  fetchSendValidateCode,
  fetchCheckValidate,
  fetchLogin,
} from './actions/login';
import { openWindow } from '@/util/util';
import { validate, toastValidate } from './util/validate';
import selCompanyList from './components/selcompanyList/index';

export default {
  name: 'Login',
  components: {
    'sel-company-list': selCompanyList,
  },
  data() {
    return {
      loginState: true,
      showPwd: true,
      loginInfo: {},
      appLoginInfo: {},
      sendAuthCode: true,
      auth_time: 0,
      company: [],
      logoClick: 0,
      companyList: [],
      showModalFlag: false,
      tapcount: 1,
      netConcat: false,
      showRegister: false,
    };
  },
  computed: {
    hasLoginHistory() {
      let loginHistory = [];
      if (JE.getLSItem('loginHistory')) {
        loginHistory = JSON.parse(JE.getLSItem('loginHistory')) || [];
      }
      return loginHistory.length > 0;
    },
  },
  async created() {
    // 首页返回键处理
    // 处理逻辑：1秒内，连续两次按返回键，则退出应用；
    let first = null;
    // const oldBack = mui.back;
    mui.back = function back() {
      // 首次按键，提示‘再按一次退出应用’
      if (!first) {
        first = new Date().getTime();
        mui.toast('再按一次退出应用');
        setTimeout(() => {
          first = null;
        }, 1000);
      } else if (new Date().getTime() - first < 1000) {
        plus.runtime.quit();
      }
    };
    Waves.init();
    document.addEventListener('pause', () => {
    }, false);
    document.addEventListener('resume', () => {
      if (JE.getLSItem('activeViewPwd')) {
        openWindow({
          url: './pages_forgetPwd_index.html',
          id: '__forgetPwdView',
          title: '忘记密码',
        });
      }
      if (JE.getLSItem('activeViewSet')) {
        openWindow({
          url: './pages_setNewPwd_index.html',
          id: '__setNewPwdView',
          title: '忘记密码',
        });
      }
    }, false);
  },
  mounted() {
    // 登陆页渲染完成后 关闭splash
    const token = JE.getLSItem('authorization');
    // 读取本地存储，检查是否为首次启动
    const showGuide = JE.getLSItem('lauchFlag');
    if (!token && showGuide) {
      plus.navigator.closeSplashscreen();
    }
    this.loginHistory(true);
    const that = this;
    mui.plusReady(() => {
      document.addEventListener('netchange', that.wainshow, false);
    });
    this.showRegister = JE.getSystemConfig('JE_SHOW_REGISTER') == 1; // 从系统变量中获取是否要开启注册页面 用户APP上架审核用
  },
  methods: {
    inputfocus() {
      if (!mui.os.ios) {
        if (document.querySelector('.mui-toast-container')) {
          document.querySelector('.mui-toast-container').classList.add('mui-toast-container1');
        }
      }
    },
    // 断网监听
    wainshow() {
      if (plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
        mui.toast('请检查网络');
        this.btnReset();
        this.netConcat = true;
      } else {
        this.netConcat = false;
      }
    },
    // 展示公司列表
    showFlag() {
      this.showModalFlag = false;
      setTimeout(() => {
        this.btnReset();
      }, 10);
    },
    // 设置服务器地址
    setServerPath() {
      JE.getHomePage().evalJS('APP.start.debug("login");');
    },
    // 登录记录，只获取前五
    loginHistory(init) {
      let loginHistory = [];
      const buttons = [];
      if (JE.getLSItem('loginHistory')) {
        loginHistory = JSON.parse(JE.getLSItem('loginHistory')) || [];
      }
      if (loginHistory.length > 5) {
        loginHistory = loginHistory.slice(0, 6);
      }
      for (let i = 0; i < loginHistory.length; i += 1) {
        buttons.push({ title: loginHistory[i] });
      }
      if (init) {
        this.$set(this.loginInfo, 'phone', loginHistory[0]);
        return;
      }
      plus.nativeUI.actionSheet({ title: '请选择', cancel: '取消', buttons }, (e) => {
        if (e.index > 0) {
          this.$set(this.loginInfo, 'phone', buttons[e.index - 1].title);
        }
      });
    },
    // 登录
    async login() {
      this.closePage();
      if (!mui.os.ios) {
        if (document.querySelector('.mui-toast-container')) {
          document.querySelector('.mui-toast-container').classList.remove('mui-toast-container1');
          mui('.mui-toast-container').hide();
        }
      }
      if (this.netConcat) {
        this.btnReset();
        mui.toast('请检查网络');
        return;
      }
      // 页面失去焦点
      mui('.mui-btn').button('loading');
      Waves.attach('.login-btn', ['waves-button', 'waves-float']);
      if (
        !toastValidate('手机号', validate.isNull(this.loginInfo.phone))
        || (this.loginState && !toastValidate('密码', validate.isNull(this.loginInfo.pwd)))
        || (!this.loginState && !toastValidate('短信动态验证码', validate.isNull(this.loginInfo.validateCode)))
      ) {
        mui('.mui-btn').button('reset');
        return false;
      }
      // 校验验证码
      if (!this.loginState) {
        const validateCodeRes = await fetchCheckValidate({
          email: this.loginInfo.phone,
          type: 'PHONE',
          cz: 'LOGIN',
          code: this.loginInfo.validateCode,
        });
        if (!validateCodeRes.success) {
          mui.toast(validateCodeRes.message);
          mui('.mui-btn').button('reset');
          return false;
        }
        this.sendLogin('code', {
          j_username: this.loginInfo.phone,
          j_code: this.loginInfo.validateCode,
          state: '',
        });
      } else {
        this.sendLogin('pwd', {
          j_username: this.loginInfo.phone,
          j_password: this.loginInfo.pwd,
        });
      }
    },
    // 发送登录
    async sendLogin(type, params) {
      let param = {};
      if (type === 'code') {
        param = {
          j_username: params.j_username,
          loginType: 'PHONE',
          j_code: params.j_code,
          state: params.state,
          isNew: 1,
        };
      } else if (type === 'pwd') {
        param = {
          j_username: params.j_username,
          j_password: params.j_password,
          isNew: 1,
        };
      }
      const res = await fetchLogin(param);
      if (res.success) {
        if (res.code === 'OK') {
          JE.setLSItem('authorization', res.obj);
          const loginPhone = this.loginInfo.phone || '';
          if (loginPhone) {
            let set;
            if (JE.getLSItem('loginHistory')) {
              set = new Set(JSON.parse(JE.getLSItem('loginHistory')));
            } else {
              set = new Set();
            }
            set.add(loginPhone);
            JE.setLSItem('loginHistory', JSON.stringify(Array.from(set)));
          }
          // 登陆成功后传值给首页 请求接口渲染数据，渲染完成后回传登陆页关闭登陆页
          this.showModalFlag = false;
          this.$refs.inputBlurName.blur();
          this.$refs.inputBlurPassword.blur();
          plus.webview.getLaunchWebview().evalJS('APP.start.openHome()');
          this.$refs.inputBlurName.blur();
          this.$refs.inputBlurPassword.blur();
          mui('.mui-btn').button('reset');
        } else if (res.code === 'CHECK') {
          this.btnReset();
          this.showModalFlag = true;
          this.companyList = JSON.parse(res.obj);
        }
      } else {
        this.showModalFlag = false;
        this.btnReset();
        mui.toast(res.message);
      }
    },
    // 获取验证码
    async getValidateCode() {
      if (
        !toastValidate('手机号/账户', validate.isNull(this.loginInfo.phone))
        || !toastValidate('', validate.isPhone(this.loginInfo.phone), '手机号格式不正确')
      ) {
        return false;
      }

      if (this.sendAuthCode) {
        const res = await fetchSendValidateCode({
          email: this.loginInfo.phone,
          type: 'PHONE',
          cz: 'LOGIN',
        });
        mui.toast(res.message);
        if (res.success) {
          this.sendAuthCode = false;
          this.auth_time = 59;
          const authTimetimer = setInterval(() => {
            this.auth_time--;
            if (this.auth_time <= 0) {
              this.sendAuthCode = true;
              clearInterval(authTimetimer);
            }
          }, 1000);
        }
      }
    },
    errorMsg(code, count) {
      const loginErrMsg = {
        1001: {
          cn1: '账号或者密码错误超过[',
          cn2: ']次,请使用其他方式登录!',
          en1: 'Account or password error more than [',
          en2: '] times, please use other way to log in!',
        },
        1002: {
          cn1: '账号或密码错误,您还剩余[',
          cn2: ']次个人密码登录机会!',
          en1: 'Account number or password error, you still have left [',
          en2: '] personal password login opportunity!',
        },
        1003: {
          cn: '验证码错误!',
          en: 'Verification code error!',
        },
        1004: {
          cn: '用户未认证!',
          en: 'User not authenticated!',
        },
        1005: {
          cn: '认证失败!',
          en: 'Authentication failed!',
        },
        1006: {
          cn: '帐号或密码错误!',
          en: 'Wrong account or password!',
        },
        1007: {
          cn: '状态机不对，请重新登录!',
          en: 'The state machine is not correct, please login again!',
        },
      };
      if ('1001,1002'.indexOf(code) > -1) {
        const cn = loginErrMsg[code].cn1 + count + loginErrMsg[code].cn2;
        mui.toast(cn);
      } else {
        mui.toast(loginErrMsg[code].cn);
      }
    },
    // 忘记密码
    forgetPwd() {
      openWindow({
        url: './pages_forgetPwd_index.html',
        id: '__forgetPwdView',
        title: '忘记密码',
      });
    },
    btnReset() {
      this.$refs.inputBlurName.blur();
      this.$refs.inputBlurPassword.blur();
      mui('.mui-btn').button('reset');
    },
    closePage() {
      const forgetPwdView = plus.webview.getWebviewById('__forgetPwdView');
      const setNewPwdView = plus.webview.getWebviewById('__setNewPwdView');
      if (setNewPwdView || forgetPwdView) {
        plus.webview.close(setNewPwdView);
      }
    },
  },
};
</script>
